<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Admin\Agent;
use App\Models\Coupon;
use App\Models\IntegralLog;
use App\Models\ShopClock;
use App\Models\ShopCoupon;
use App\Service\ShopClockService;
use App\Service\AgentService;
use App\Service\HttpService;
use App\Models\ActivityRules;
use App\Models\Shop;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Models\Banner;

class ShopClockController extends Controller
{

    /**
     *
     * @param AgentService $agentService
     * @param HttpService $httpService
     * @author Bryant
     * @date 2020-09-02 16:25
     *
     * 用户门店打卡
     */
    public function userClock(ShopClockService $shopclockService,HttpService $httpService,ActivityRules $activityRules)
    {
        $mobile = request('mobile');

        if (!checkMobile($mobile)) {
            return tips(-1, 'error', '手机号码格式不正确');
        }

        // 判断是否是会员
        $isUser = $this->isUser($httpService,$mobile);
        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }

        // 获取经纬度
        $lng = request('lng');
        $lat = request('lat');
        if (!$lng || !$lat) {
            return tips(-1,'error','缺少参数');
        }

        // 活动的星信息
        $active_id = request('active_id',1);
        $activityInfo = $activityRules->where('id',$active_id)->first();


        if ($activityInfo['status'] != 1) {

            return tips(-1,'error','该活动已结束');
        }
        $start_time = strtotime($activityInfo['start_time']);

        $end_time = strtotime($activityInfo['end_time']);

        if (time() <$start_time || time() > $end_time) {

            return tips(-1,'error','不在活动期');
        }
        // 获取500范围内的门店
        $distance = $activityInfo['distance'] ?? 500; //测试数据

        $field = "*,round((
                            6371392.89 * acos (
                            cos ( radians({$lat}) )
                             * cos( radians(shop_lat))
                             * cos( radians(shop_lng) - radians({$lng}) )
                             + sin ( radians({$lat}))
                             * sin( radians(shop_lat))
                             )), 0) AS distance";
        $list = DB::table('shop')->selectRaw($field)

            ->whereRaw("round((
                            6371392.89 * acos (
                            cos ( radians({$lat}) )
                             * cos( radians(shop_lat ) )
                             * cos( radians(shop_lng) - radians({$lng}) )
                             + sin ( radians({$lat}) )
                             * sin( radians( shop_lat ) )
                             )), 0) <= {$distance}")
            ->orderBy('distance')
            ->paginate(1);
        if (!$list->items()) {

            return tips(-1,'error','该附近没有门店');
        }
        $data = $list->items();
        // 加入数据
        foreach($data as $key=>$value){
            // 判断有更新没有加入
            $datas = [
                'shop_id' => $value->id,
                'mobile' => $mobile,
                'created_at' => date('Y-m-d H:i:s',time()),
                'updated_at' => date('Y-m-d H:i:s',time()),
                'shop_code' => $value->shop_code,
            ];
            $result = ShopClock::where('shop_id',$value->id)->where('mobile',$mobile)->first();

            if ($result) {
                // 更新打卡时间
                $res = ShopClock::where('shop_id', $value->id)->where('mobile', $mobile)->update($datas);
            } else {
                $res =  ShopClock::where('shop_id', $value->id)->where('mobile', $mobile)->create($datas);
            }
        }

        if ($res) {
            return tips(1,'success','打卡成功');
        } else {
            return tips(-1,'error','打卡失败');
        }


    }

    /**
     *
     * @author Bryant
     * @date 2020-10-13 15:24
     *
     * 获取数量 判断是否可以领取积分
     */
    public function isClock(ActivityRules $activityRules,ShopClock $shopClock,HttpService $httpService,IntegralLog $integralLog)
    {
        $mobile = request('mobile');

        // 获取本月开始时间和结束时间
        $date = date('Y-m-d');
        $firstDay = date('Y-m-01 00:00:00', strtotime($date));  //本月第一天
        $lastDay = date('Y-m-d 23:59:59', strtotime("$firstDay +1 month -1 day")); //本月最后一天
        // 活动的星信息
        $active_id = request('active_id',1);
        $activityInfo = $activityRules->where('id',$active_id)->first();

        if ($activityInfo['status'] != 1) {

            return tips(-1,'error','该活动已结束');
        }
        $start_time = strtotime($activityInfo['start_time']);

        $end_time = strtotime($activityInfo['end_time']);

        if (time() <$start_time || time() > $end_time) {

            return tips(-1,'error','不在活动期');
        }

        //统计本月打卡的数量
        $num = $shopClock->where('mobile',$mobile)->whereBetween('created_at',[$firstDay,$lastDay])->count('id');

        if ($num < $activityInfo['condition']) {

            return tips(-1,'error','您的打卡数量不足,暂时无法兑换积分');
        }

        // 判断本月是否兑换过

        $is_get = $integralLog->where('mobile',$mobile)->where('from_type',1)->whereBetween('created_at',[$firstDay,$lastDay])->count('id');

        if ($is_get >= 1) {
            return tips(-1,'error','本月您已经领取过了');
        }

        //获取用户的会员号
        $str = request(['queryStr']);

        $userInfo = $this ->getMemberCard($httpService,$str);

        if ($userInfo['Statu'] !=1) {

            return tips(-1,'error',$userInfo['Msg']);
        }

        $userCard = $userInfo['VCardNO'];

        if (!$userCard) {
            return tips(-1,'error','您暂时没有领用会员卡，请前往周黑鸭公众号领用会员卡');
        }

        $nums = rand(100000,999999);
        // 操作积分
        DB::beginTransaction();

        try {
            // 获取CRM 的数据
            $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址
            $param = [
                'action' => 'ZRFC_INTERACTIONPOINTS_PAY', //访问的方法
                'ZZCHANNEL' => "HNX", // 渠道
                'PARTNER_ID' =>$userCard, // 会员号
                'MOB_NUMBER' =>"",
                'ZZAUART' => 'S02',
                'ZZVBELN' => date('YmdHis',time()).$nums,
                'ZZCPSYDAT' => date('YmdHis',time()),
                'ZEPOINT_ADD' => $activityInfo['point'],
                'ZEPOINT_RED' => '',
                'ZEPRODUCTS_ID' => 'HDJF',
                'ZZCPSTORE' => "SZ09997",

            ];
            $param = json_encode($param,true);

            $res = $this->curl_open($getUrl,$param);

            if ($res['errcode'] == 4002) {

                $res = $this->curl_open($getUrl,$param);
            }

            if($res['rtval']['E_RETURN']['MSTYP'] != 'S'){

                return tips(-1,'error',$res['rtval']['E_RETURN']['MSMEG']);
            }

            $data = [

                'integral' =>$activityInfo['point'],
                'from_type' => 1, // 门店打卡
                'type' => 1, //收入
                'mobile' => $mobile,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
            // 加入记录表
            $result = $integralLog->insert($data);


            if (!$result) {

                throw new \Exception('添加数据有问题');
            }
        } catch (\Exception $e) {

            DB::rollBack();
            return tips(-1,'error',$e->getMessage());
        }
        DB::commit();

        return tips(1,'success','兑换成功');


    }


    /**
     *
     * @author Bryant
     * @date 2020-10-14 14:03
     *
     * 获取打卡的门店信息
     */
    public function  getShopList(HttpService $httpService,ShopClock $shopClock,ActivityRules $activityRules)
    {
        $mobile = request('mobile');

        $active_id = request('active_id',1);

        $activityInfo = $activityRules->where('id',$active_id)->first();

        $banner = Banner::where('type',2)->get();

        $date = date('Y-m-d');
        $firstDay = date('Y-m-01 00:00:00', strtotime($date));  //本月第一天
        $lastDay = date('Y-m-d 23:59:59', strtotime("$firstDay +1 month -1 day")); //本月最后一天

        // 判断是否是会员
        $isUser = $this->isUser($httpService,$mobile);

        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }
        $list =$shopClock->where('mobile',$mobile)->whereBetween('created_at',[$firstDay,$lastDay])->with('shop')->paginate();


        return tips(-1,'success',[
            'list' => $list,
            'active' => $activityInfo,
            'banner' => $banner,
            'img_url' => img_url(),
        ]);
    }

    /**
     *
     * @author Bryant
     * @date 2020-10-17 18:56
     *
     * 门店打卡兑换优惠券
     */
    public function getCoupon(HttpService $httpService,Coupon $coupon,ActivityRules $activityRules,ShopClock $shopClock,ShopCoupon $shopCoupon)
    {
        $mobile = request('mobile');

        if (!checkMobile($mobile)) {
            return tips(-1, 'error', '手机号码格式不正确');
        }

        // 判断是否是会员
        $isUser = $this->isUser($httpService,$mobile);
        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }

        // 获取本月开始时间和结束时间
        $date = date('Y-m-d');
        $firstDay = date('Y-m-01 00:00:00', strtotime($date));  //本月第一天
        $lastDay = date('Y-m-d 23:59:59', strtotime("$firstDay +1 month -1 day")); //本月最后一天
        // 活动的星信息
        $active_id = request('active_id',1);
        $activityInfo = $activityRules->where('id',$active_id)->first();

        if ($activityInfo['status'] != 1) {

            return tips(-1,'error','该活动已结束');
        }
        $start_time = strtotime($activityInfo['start_time']);

        $end_time = strtotime($activityInfo['end_time']);

        if (time() <$start_time || time() > $end_time) {

            return tips(-1,'error','不在活动期');
        }

        //统计本月打卡的数量
        $num = $shopClock->where('mobile',$mobile)->whereBetween('created_at',[$firstDay,$lastDay])->count('id');

        if ($num < $activityInfo['condition']) {

            return tips(-1,'error','您的打卡数量不足,暂时无法兑换积分');
        }


        // 查询优惠券的相关的信息
        $couponInfo = $coupon -> where('coupon_code',$activityInfo['coupon_code'])->first();

        if ($couponInfo['coupon_num'] <= 0) {

            return tips(-1,'error','优惠券已经领取完');
        }

        $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址
        $param = [
            'action' => 'DT_COUPONISSUANCE_REQ',
            'ZCOUPXH' => $activityInfo['coupon_code'],
            //'ZPARTNER_ID'=> "",
            'ZCPNUMTO' =>"1",
            'ZCPBDDAT' =>date('Y-m-d',time()),
            'ZREFIELD2' => 'HNX',
            'ZREFIELD3' => $mobile

        ];
        $param = json_encode($param,true);
        //dd($param);
        $res = $this->curl_open($getUrl,$param);
        //dd($res);
        if($res['rtval']['T_RETURN'][0]['TYPE'] == 'S'){
            $coupon_num = $res['rtval']['T_OUT_ISSUANCE'][0]['ZZCPIDO'] ?? 0;
        }else{
            return tips(-1,'error',$res['rtval']['T_RETURN'][0]['MESSAGE']);
        }

        //加入门店优惠券记录表

        DB::beginTransaction();

        try {

            $data = [
                'coupon_code' => $activityInfo['coupon_code'],
                'coupon_num' =>$coupon_num,
                'mobile' => $mobile,
                'created_at' => date('Y-m-d H:i:s',time())
            ];

            $res = $shopCoupon->insert($data);

            DB::table('coupon')->where('coupon_code',$activityInfo['coupon_code'])->decrement('coupon_num');

        } catch (\Exception $e) {
            DB::rollBack();
            return tips(-1,'error',$e->getMessage());
        }
        DB::commit();

        return tips(1,'success','领取成功');

    }

    /**
     *
     * @param Shop $shop
     * @author Bryant
     * @date 2020-10-19 17:04
     *
     * 获取附近门店
     */
    public function getShop(Request $request,Shop $shop)
    {
        $lng = request('lng');

        $lat = request('lat');

        $distance = request('distance',2000);

        $keyword = request('keyword');

        $field = "*,round((
                            6371392.89 * acos (
                            cos ( radians({$lat}) )
                             * cos( radians(shop_lat))
                             * cos( radians(shop_lng) - radians({$lng}) )
                             + sin ( radians({$lat}))
                             * sin( radians(shop_lat))
                             )), 0) AS distance";
        $list = DB::table('shop')->selectRaw($field)
            ->orderBy('distance')
            ->whereRaw("round((
                            6371392.89 * acos (
                            cos ( radians({$lat}) )
                             * cos( radians(shop_lat ) )
                             * cos( radians(shop_lng) - radians({$lng}) )
                             + sin ( radians({$lat}) )
                             * sin( radians( shop_lat ) )
                             )), 0) <= {$distance}")
            ->where('shop_name','like',"%$keyword%")
            ->paginate();
        if (!$list->items()) {
            return tips(-1,'error','该附近没有门店');
        }

        return tips(1,'success',$list);
    }


}
